package com.baicaoyuan.web.service;

import com.baicaoyuan.web.common.StringUtils;
import com.baicaoyuan.web.common.TimeUtils;
import com.baicaoyuan.web.enums.StatusEnum;
import com.baicaoyuan.web.model.NoticeDO;
import com.baicaoyuan.web.repository.NoticeRepository;
import com.baicaoyuan.web.request.br.BNoticeRequest;
import com.baicaoyuan.web.response.NoticeResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 功能描述：
 *
 * @author 罗富祥
 * 创建时间： 2018/1/4
 */
@Service
public class NoticeService {

    @Autowired
    NoticeRepository noticeRepository;

    public List<NoticeResponse> getNotices(Integer page, Integer size) {
        List<NoticeDO> list = this.noticeRepository.getNotices((page - 1) * size, size);
        List<NoticeResponse> result = new ArrayList<>();
        list.forEach(x -> {
            NoticeResponse r = new NoticeResponse();
            BeanUtils.copyProperties(x, r);
            result.add(r);
        });

        return result;
    }

    public void save(BNoticeRequest request) {
        NoticeDO notice = new NoticeDO();
        notice.setTitle(request.getTitle());
        notice.setContent(request.getContent());
        notice.setCreateTime(TimeUtils.getCurrentTime());
        notice.setStatus(StatusEnum.NORMAL.getStatus());
        Objects.requireNonNull(this.noticeRepository.save(notice));
    }

    public void edit(BNoticeRequest request) {
        Objects.requireNonNull(request);
        Objects.requireNonNull(request.getId());

        NoticeDO notice = this.noticeRepository.findOne(request.getId());
        BeanUtils.copyProperties(request, notice);
        Objects.requireNonNull(this.noticeRepository.save(notice));

    }

    public void delete(Long id) {
        Integer i = this.noticeRepository.updateStatus(id, StatusEnum.DELETE.getStatus());
        if (i == 0) {
            throw new RuntimeException();
        }
    }

    public Integer getCountOfAll() {
        return this.noticeRepository.countAllByStatusIsNot(StatusEnum.DELETE.getStatus());
    }
}

